package com.jackyzgy.test.code;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * DES加密解密
 * 
 * @author yedecan
 * @version 1.7
 */
public class DesEncrypt {
	private static final Log log = LogFactory.getLog(DesEncrypt.class);
	
    private static final String CRYPT_ALGORITHM = "DES";
    
	private static String key = "p5rea7pp";
    
    public DesEncrypt() {
    	
	}
    
    public DesEncrypt(String key){
    	this.key = key;
    }
    
    /**
     * DES解密
     * @param value
     * @return 
     */
    public static String decrypt(String value) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            
            byte[] decodedByte = Base64.decodeBase64(value.getBytes());
            byte[] decryptedByte = cipher.doFinal(decodedByte);            
            return new String(decryptedByte);
        } catch(Exception e) {
        	log.error(e.getMessage(), e);
        	e.printStackTrace();
            return "";
        }
    }
    
    /**
     * DES加密
     * @param value
     * @return 
     */
    public static String encrypt(String value) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), CRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            
            byte[] encryptedByte = cipher.doFinal(value.getBytes());
            byte[] encodedByte = Base64.encodeBase64(encryptedByte);
            return new String(encodedByte);
        } catch(Exception e) {
        	log.error(e.getMessage(), e);
            return "";
        }
    }
    
    public static void main(String[] args) {
		DesEncrypt encrypt = new DesEncrypt();
		System.out.println(encrypt.encrypt("要加密的字符串 test"));
		String decrypt = encrypt.decrypt(encrypt.encrypt("要加密的字符串 test"));
		System.out.println(decrypt);
	}
    
}
